package com.whfc.mach.queue;

import com.whfc.common.constant.QueueConst;
import com.whfc.common.obd.ObdDataUtil;
import com.whfc.common.obd.ObdFrame;
import com.whfc.common.obd.ObdFrameItem;
import com.whfc.common.third.map.MapApi;
import com.whfc.common.third.map.MapLoc;
import com.whfc.common.util.Gps;
import com.whfc.common.util.JSONUtil;
import com.whfc.mach.dto.iot.MachMsg0x06;
import com.whfc.mach.entity.AppDeviceObdLog;
import com.whfc.mach.manager.ObdDataMgr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description: Obd硬件数据批量传输
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/12/2 11:59
 */
@Component
@RabbitListener(queues = QueueConst.MACH_MSG_0X06)
public class MachMsg0x06QueueMessageListener {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ObdDataMgr obdDataMgr;

    @Autowired
    private MapApi mapApi;

    @RabbitHandler
    public void process(String msg) {
        try {
            logger.debug("mach_msg_0x06,{}", msg);
            MachMsg0x06 reqMsg = JSONUtil.parseObject(msg, MachMsg0x06.class);
            AppDeviceObdLog obdLog = this.translate(reqMsg);
            obdDataMgr.addObdData(obdLog, reqMsg.getFrameList());
        } catch (Exception ex) {
            logger.error("mach_msg_0x06,消息处理失败", ex);
        }
    }

    /**
     * 转换数据
     *
     * @param reqMsg
     * @return
     */
    private AppDeviceObdLog translate(MachMsg0x06 reqMsg) {
        List<ObdFrame> frameList = reqMsg.getFrameList();
        for (ObdFrame obdFrame : frameList) {
            List<ObdFrameItem> obdFrameItemList = ObdDataUtil.parseObdData(obdFrame.getFrameId(), obdFrame.getFrameData());
            String frameDataDetail = JSONUtil.toString(obdFrameItemList);
            obdFrame.setFrameDataDetail(frameDataDetail);
        }

        Gps gcj02Gps = mapApi.translateToGcj02(reqMsg.getLngWgs84(), reqMsg.getLatWgs84());
        if (gcj02Gps != null) {
            reqMsg.setLng(gcj02Gps.getLng());
            reqMsg.setLat(gcj02Gps.getLat());
            MapLoc location = mapApi.geocode(gcj02Gps.getLng(), gcj02Gps.getLat());
            if (location != null) {
                reqMsg.setProvince(location.getProvince());
                reqMsg.setCity(location.getCity());
                reqMsg.setLocation(location.getAddress());
            }
        }

        AppDeviceObdLog log = new AppDeviceObdLog();
        BeanUtils.copyProperties(reqMsg, log);
        return log;
    }
}
